<?php
namespace Util;
use Think\Upload as tupload; 
use Think\Image;
class Upload{
    //访问修饰符 public protected private
    private $maxSize=0;
    private $rootPath='';
    public $checkName='check';//将要上传的图片，检测隐藏域
    public $checkedName='checked';//已上传的图片，检测的隐藏域name
    public $thumbSize=200;
    public $waterFile='./Public/logo.png';
    
    function __construct($size=1048576,$path=''){
        $this->maxSize=$size;
        
        if(empty($path)){
            $this->rootPath='./Public/Uploads/'.MODULE_NAME.'/';
        }else{
            $this->rootPath=$path;
        }
        if(!is_dir($this->rootPath)){
            mkdir($this->rootPath,777,true);
        }
    }
    
    function add(){
      
        $config=array(
            'maxSize'=>$this->maxSize,//文件最大的大小
            'exts'=>array('jpg','jpeg','gif','png'),//图片的格式
            'rootPath'=>$this->rootPath//保存目录
            
        );
        $upload=new tupload($config);//实例化上传类
        $result=$upload->upload();//上传文件，返回上传的信息数组
        
        $data=array();//已上传文件保存的数组原图
        $thumbs=array();//已上传文件的微缩图
        $waters=array();//已上传的水印图
        //ob_clean();
        //print_r(I('post.'.$this->checkName));die;
        if($result){//判断返回值 array false
            foreach ($result as $k=>$v){
                $file=$this->rootPath.$v['savepath'].$v['savename'];
               
                if(in_array($k,I('post.'.$this->checkName))){
                    $data[]=$file;
                    $img=new Image();
                    //微缩图
                   if($thumbs->thumbSize>0){
                       $newfile=$this->rootPath.$v['savepath'].'thumb_'.$v['savename'];
                       $img->open($file)->thumb($thumbs->thumbSize, $thumbs->thumbSize)->save($newfile);
                       $thumbs[]=$newfile;
                   }
                   //图片水印
                   if(!empty($this->waterFile)){
                       $newfile=$this->rootPath.$v['savepath'].'water_'.$v['savename'];
                       $img->open($file)->water($this->waterFile,7,30)->save($newfile);
                       $waters[]=$newfile; 
                   }
                }else{
                    if(is_file($file)){
                        unlink($file);
                    }
                }
            }
        }
        return array(
            'images'=>$data,
            'thumbs'=>$thumbs,
            'waters'=>$waters,
            'error'=>$upload->getError()
        );
    }
    function check($images){
        $checked=I('post.'.$this->checkedName);
        foreach ($images as $k=>$v){
            if(!in_array($k, $checked)){
                if(is_file($v)){
                    unlink($v);
                }
                unset($images[$k]);
            }
        }
        return $images;
    }
    function del($images){
        foreach ($images as $v){
            if(is_file($v)){
                unlink($v);
            }
        }
        
    }
}